import { Article, Channel } from '@/types/data'
import { HomeAction } from '@/types/store'
type HomeState = {
  userChannels: Channel[]
  allChannels: Channel[]
  activeChannelId: number
  channelArticles: {
    [key: number]: {
      timestamp: string
      articles: Article[]
    }
  }
}

const initialValue: HomeState = {
  userChannels: [],
  allChannels: [],
  activeChannelId: 0,
  channelArticles: {}
}

export default function homeReducer(
  state = initialValue,
  action: HomeAction
): HomeState {
  if (action.type === 'home/set_user_channels') {
    return {
      ...state,
      userChannels: action.payload
    }
  }

  if (action.type === 'home/set_all_channels') {
    return {
      ...state,
      allChannels: action.payload
    }
  }

  if (action.type === 'home/set_active_channel') {
    return {
      ...state,
      activeChannelId: action.payload
    }
  }

  if (action.type === 'home/set_channel_articles') {
    const { channel_id, timestamp, articles } = action.payload

    // 1.获取之前加载的文章列表数据
    const oldArticles = state.channelArticles[channel_id]?.articles || []

    return {
      ...state,
      channelArticles: {
        ...state.channelArticles,
        [channel_id]: {
          timestamp,
          // 合并老数据
          articles: [...oldArticles, ...articles]
        }
      }
    }
  }

  if (action.type === 'home/refresh_articles') {
    const { channel_id, timestamp, articles } = action.payload
    return {
      ...state,
      channelArticles: {
        ...state.channelArticles,
        [channel_id]: {
          timestamp,
          articles: [...articles]
        }
      }
    }
  }

  return state
}
